package com.example.black.myapplication.mynet;

import android.util.Log;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 网络框架主体
 */
public class NetWorkManager {
    String Tag = NetWorkManager.class.getSimpleName();
    //队列
    private LinkedBlockingDeque<Runnable> deque = new LinkedBlockingDeque<>();

    private static NetWorkManager netWorkManager = new NetWorkManager();
    public DelayQueue<HttpTask> delayQueue = new DelayQueue<>();
    private ThreadPoolExecutor executor;
    private NetWorkManager(){
        executor = new ThreadPoolExecutor(3, 10, 15,
                TimeUnit.SECONDS, new ArrayBlockingQueue<>(4), new RejectedExecutionHandler() {
            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                addTask(r);
            }
        });
        executor.execute(communicateThread);
        executor.execute(delayThread);
    }

    public void addTask(Runnable r) {
        try {
            deque.put(r);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private  Runnable communicateThread = new Runnable() {
        @Override
        public void run() {
            while (true){
                Runnable runnable = null;
                try {
                    runnable = deque.take();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (runnable == null){
                    return;
                }
                executor.execute(runnable);
//                try {
//                    Thread.sleep(1000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
            }

        }
    };

    private  Runnable delayThread = new Runnable() {
        @Override
        public void run() {
            while (true){
                HttpTask runnable = null;
                try {
                    runnable = delayQueue.take();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (runnable == null){
                    return;
                }
                if (runnable.count >= 3){
                    Log.e(Tag, "run: 超过3次丢弃");
                    return;
                }
                runnable.count++;
                Log.e(Tag, "run: 失败，重新添加到队列"+runnable.count);
                addTask(runnable);

            }

        }
    };
    public void addDelayTask(HttpTask task) {
        task.setDelayTime(3000);
        delayQueue.offer(task);
    }
    public static NetWorkManager getNetWorkManager() {
        return netWorkManager;
    }
}
